#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : project
@File : mysql111.py.py
@Author : 薄荷糖
@Time : 2025/9/9 18:05  
@脚本说明 : 
"""
import threading
import pymysql
import ipaddress


def scan_mysql(host="127.0.0.1", port=3306, user="root", password="", connect_timeout=5):
    try:
        pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            connect_timeout=connect_timeout,
            database="information_schema",
            charset="utf8",
            autocommit=True,
        )
        print(f"[+] {host}:{port} 存在MySQL数据库弱口令 -> {user} / {password}")
    except Exception as e:
        pass

def run_mysql(host, port, users, passwds):
    try:
        threads = []
        for user in users:
            # 读取密码字典
            for passwd in passwds:
                # 弱口令扫描 注意需要去除空白符
                t = threading.Thread(target=scan_mysql, args=(host, port, user.strip(), passwd.strip()))
                t.start()
                threads.append(t)
        for t in threads:
            t.join()
    except:
        pass

def run_mysql_for_host_or_cidr(host_input, port, users, passwds):
    try:
        # 尝试解析为单个 IP
        ip = ipaddress.IPv4Address(host_input)
        print(f"[*] 开始扫描单个 MySQL 主机: {ip}")
        run_mysql(str(ip), port, users, passwds)
    except ipaddress.AddressValueError:
        try:
            # 尝试解析为 CIDR 网段
            network = ipaddress.IPv4Network(host_input, strict=False)
            print(f"[*] 开始扫描 MySQL 网段: {network}")
            for ip in network.hosts():
                run_mysql(str(ip), port, users, passwds)
        except ipaddress.NetmaskValueError:
            print(f"[-] 错误的 IP 或 CIDR 格式: {host_input}，请检查格式（如 192.168.1.1 或 192.168.1.0/24）")
    except Exception as e:
        print(f"[-] 扫描过程中发生未知错误: {e}")


